﻿var socket;
var allusers = {};
var username;
var usermouses = [];
var context;
var drawing = false;
var room = { index: getQueryStringByName('room') };
var onlineUserTemplate;
var userGridCellTemplate;
var lastPoint = null;
var user;
var sendDrawing = true;

$(function () {
  if (room.index.length > 0) {
    socket = io.connect('http://localhost:4579');
  }
  socket.on('connect', function () {
    $('#mainArea').append($('<p>').append('<em>You have connected to the server.<em>'));
    $.prompt('Welcome to IdrawUguess!', { prefix: 'impromptu', callback: mycallbackfunc });
    onlineUserTemplate = $('#onlineUserTemplate').html();
    userGridCellTemplate = $('#userGridCellTemplate').html();
    bindUserInputs();
  });

  socket.on('notice', function (msg) {
    $.prompt(msg, { prefix: 'impromptu', callback: function (e, v, m, f) {
      if (msg.indexOf('win!') != -1 || msg.indexOf('less than 2')) {
        sendDrawing = true;
        $('#drawControlPanel').css('visibility', 'hidden');
        $('#room').show();
        $('#game').hide();
      }
    } 
    });
  });

  socket.on('roominfo', function (room) {
    room = room;
    $('#nicknames').empty();
    userGrids.empty();
    for (var i = 0; i < room.users.length; i++) {
      $('#nicknames').append(getUserHtml(room.users[i]));
      if (room.users[i].name == username) {
        user = room.users[i];
      }
    }

    userGrids.each(function (index) {
      if (index < room.users.length) {
        var html = userGridCellTemplate.replace('{Image}', 'images/user_default.jpg')
        .replace('{Name}', room.users[index].name);
        $(this).html(html);
      } else {
        var html = userGridCellTemplate.replace('{Image}', '').replace('{Name}', '');
        $(this).html(html);
      }
    });

    $('.roominfo').text(room.name);
    if (user.isOwner) {
      $('#actionBtn').text('Start');
      if (room.status == 'ready') {
        $('#actionBtn').removeClass('disabled');
      } else {
        $('#actionBtn').addClass('disabled');
      }
    }
    else {
      if (room.status == 'playing') {
        $('#actionBtn').addClass('disabled');
      } else {
        $('#actionBtn').removeClass('disabled');
      }
    }

    if (user.isDrawer && room.status == 'playing') {
      $('#drawControlPanel').css('visibility', 'visible');
    }
    else {
      $('#drawControlPanel').css('visibility', 'hidden');
    }

    // once the game starts
    if (room.status == 'playing') {
      if (user.isDrawer) {
        // if the user is the current drawer
        sendDrawing = true;
        $('#drawControlPanel').css('visibility', 'visible');
      } else {
        sendDrawing = false;
        $('#drawControlPanel').css('visibility', 'hidden');
      }
      $('#room').hide();
      $('#game').show();
    }
  });

  socket.on('announcement', function (room, msg) {
    $('#mainArea').append($('<p>').append($('<em>').text(msg)));
  });

  socket.on('drawWord', function (msg) {
    $.prompt('Please draw the ' + msg, { prefix: 'impromptu' });
    $('#drawword').text('Please draw the ' + msg);

  });

  socket.on('user message', function (msg) {
    $('#mainArea').append($('<div class="msg">').append($('<b>').text(msg.name), "  " + msg.msg));
  });

  socket.on('clear', function (event) {
    clearCanvas();
  });

  socket.on('palette', function (palette) {
    color = palette.color;
    lineWidth = palette.lineWidth;
    lineCap = palette.lineCap;
  });

  socket.on('mousemove', function (event) {
    usermousemove(event, event.color);
  });

  socket.on('mousedown', function (event) {
    lastPoint = { x: event.offsetX, y: event.offsetY };
    drawing = true;
  });

  socket.on('mouseup', function (event) {
    lastPoint = null;
    drawing = false;
  });

  socket.on('nicknames', function (onlineusers) {
    allusers = onlineusers;
    $('#nicknames').empty();
    for (var i = 0; i < onlineusers.length; i++) {
      $('#nicknames').append(getUserHtml(onlineusers[i]));
    }
  });

  socket.on('reconnect', function () {
    $('#mainArea').remove();
    message('System', 'Reconnected to the server');
  });

  socket.on('reconnecting', function () {
    message('System', 'Attempting to re-connect to the server');
  });

  socket.on('error', function (e) {
    message('System', e ? e : 'An unknown error occurred');
  });

  $('#actionBtn').click(function (e) {
    if ($(this)[0].className.indexOf('disabled') != -1) {
      // button is disabled
      return;
    }
    var txt = $(this).text();
    if (txt == 'Start') {
      // start game
      socket.emit('startgame', room.index);
    } else if (txt == 'Give Up') {
      socket.emit('giveupgame', room.index);
      if (room.isOwner) {
        $(this).text('Start');
      } else {
        $(this).text('Ready');
      }
      // give up
    } else if (txt == 'Ready') {
      socket.emit('ready', room.index);
      $(this).text('Cancel');
      // get ready
    } else if (txt == 'Cancel') {
      socket.emit('cancel', room.index);
      $(this).text('Ready');
      // calcel ready
    }
  });

  $('#giveUp').click(function () {
    socket.emit('giveupgame', room.index);
  });

  $('#clear').click(function () {
    socket.emit('clear', room.index);
  });

  $('#leaveBtn').click(function () {
    window.location.href = 'home.htm';
  });
});


function message(from, msg) {
  $('#mainArea').append($('<p>').append($('<b>').text(from), "  " + msg));
}

function getUserHtml(user) {
  var roleCss = user.isOwner ? 'owner' : 'normal';
  var drawerCss = user.isDrawer ? 'drawer' : 'player';
  return onlineUserTemplate.replace('{RoleCSS}', roleCss)
    .replace('{DrawerCSS}', drawerCss)
     .replace('{Name}', user.name)
    .replace('{StatusCSS}', user.status);
}

function mycallbackfunc(e, v, m, f) {
  var txt = 'Please enter your name:<br /><input type="text" id="alertName" name="alertName" value="" />';

  function mysubmitfunc(e, v, m, f) {
    if (m.alertName == "") {
      alert('name cannot be empty');
      return false;
    }
    username = m.alertName;
    socket.emit('nickname', room.index, username, function (set) {
      if (!set) {
        clear();
        $('#username').text(username);
        return;
      }
      alert('nick name already defined');
      $.prompt(txt, {
        submit: mysubmitfunc,
        buttons: { Ok: true }
      });
    });
    return true;
  }

  $.prompt(txt, {
    submit: mysubmitfunc,
    buttons: { Ok: true }
  });
}

function getQueryStringByName(name) {
  var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
  if (result == null || result.length < 1) {
    return "";
  }
  return result[1];
}